"""
API路由端点
"""
import logging
from typing import List
from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import FileResponse

from app.services.file_upload import FileUploadService
from app.services.field_extract import FieldExtractionService
from app.services.excel_export import ExcelExportService
from app.utils.helpers import create_response

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/")
async def root():
    """根路径"""
    return create_response(
        success=True,
        message="报关单字段提取API服务正在运行",
        data={
            "version": "1.0.0",
            "endpoints": {
                "health": "/health",
                "extract": "/extract",
                "extract_download": "/extract/download"
            }
        }
    )


@router.get("/health")
async def health_check():
    """健康检查"""
    return create_response(
        success=True,
        message="服务运行正常",
        data={"status": "healthy"}
    )


@router.post("/extract")
async def extract_fields(files: List[UploadFile] = File(...)):
    """
    上传文件并提取字段信息
    
    Args:
        files: 上传的文件列表
        
    Returns:
        提取结果和生成的Excel文件路径
    """
    try:
        logger.info(f"收到提取请求，文件数量: {len(files)}")
        
        if not files:
            raise HTTPException(status_code=400, detail="请至少上传一个文件")
        
        # 1. 初始化服务
        upload_service = FileUploadService()
        extract_service = FieldExtractionService()
        excel_service = ExcelExportService()
        
        # 2. 上传文件
        logger.info("步骤1: 开始上传文件")
        upload_results = await upload_service.upload_multiple_files(files)
        
        # 检查是否有文件上传成功
        success_count = sum(1 for r in upload_results if r.get("success"))
        if success_count == 0:
            raise HTTPException(status_code=500, detail="所有文件上传失败")
        
        # 获取文件ID列表
        file_ids = upload_service.get_file_ids_for_agent(upload_results)
        logger.info(f"文件上传完成，成功: {success_count}/{len(files)}")
        
        # 3. 提取字段
        logger.info("步骤2: 开始提取字段")
        extraction_results = await extract_service.extract_all_fields(file_ids)
        
        # 4. 格式化结果
        logger.info("步骤3: 格式化提取结果")
        formatted_results = extract_service.format_extraction_results(extraction_results)
        
        # 5. 生成Excel文件
        logger.info("步骤4: 生成Excel文件")
        
        # 使用第一个文件名作为前缀
        filename_prefix = "报关单提取结果"
        if upload_results and upload_results[0].get("filename"):
            first_filename = upload_results[0]["filename"]
            # 移除扩展名
            filename_prefix = first_filename.rsplit('.', 1)[0] if '.' in first_filename else first_filename
        
        excel_path = excel_service.create_extraction_excel(
            formatted_results,
            filename_prefix=filename_prefix
        )
        
        logger.info("提取流程完成")
        
        # 6. 返回结果
        return create_response(
            success=True,
            message="字段提取完成",
            data={
                "upload_summary": {
                    "total_files": len(files),
                    "successful_uploads": success_count,
                    "upload_details": upload_results
                },
                "extraction_summary": {
                    "total_fields": formatted_results["total_fields"],
                    "successful_fields": formatted_results["successful_fields"],
                    "failed_fields": formatted_results["failed_fields"]
                },
                "excel_file": excel_path,
                "fields_data": formatted_results["fields_data"],
                "raw_contents": formatted_results["raw_contents"],  # 新增: 原始content内容
                "errors": formatted_results["errors"] if formatted_results["errors"] else None
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"提取流程发生错误: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"提取失败: {str(e)}")


@router.post("/extract/download")
async def extract_and_download(files: List[UploadFile] = File(...)):
    """
    上传文件、提取字段并直接下载Excel文件
    
    Args:
        files: 上传的文件列表
        
    Returns:
        Excel文件下载
    """
    try:
        logger.info(f"收到提取并下载请求，文件数量: {len(files)}")
        
        if not files:
            raise HTTPException(status_code=400, detail="请至少上传一个文件")
        
        # 1. 初始化服务
        upload_service = FileUploadService()
        extract_service = FieldExtractionService()
        excel_service = ExcelExportService()
        
        # 2. 上传文件
        upload_results = await upload_service.upload_multiple_files(files)
        
        # 检查是否有文件上传成功
        success_count = sum(1 for r in upload_results if r.get("success"))
        if success_count == 0:
            raise HTTPException(status_code=500, detail="所有文件上传失败")
        
        # 获取文件ID列表
        file_ids = upload_service.get_file_ids_for_agent(upload_results)
        
        # 3. 提取字段
        extraction_results = await extract_service.extract_all_fields(file_ids)
        
        # 4. 格式化结果
        formatted_results = extract_service.format_extraction_results(extraction_results)
        
        # 5. 生成Excel文件
        filename_prefix = "报关单提取结果"
        if upload_results and upload_results[0].get("filename"):
            first_filename = upload_results[0]["filename"]
            filename_prefix = first_filename.rsplit('.', 1)[0] if '.' in first_filename else first_filename
        
        excel_path = excel_service.create_extraction_excel(
            formatted_results,
            filename_prefix=filename_prefix
        )
        
        # 6. 返回文件下载
        import os
        filename = os.path.basename(excel_path)
        
        return FileResponse(
            path=excel_path,
            filename=filename,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"提取并下载流程发生错误: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"提取失败: {str(e)}")


@router.post("/export/excel")
async def export_excel_from_data(request: dict):
    """
    根据前端已提取的数据生成Excel文件（快速导出）
    
    Args:
        request: 包含fields_data的字典
        
    Returns:
        Excel文件下载
    """
    try:
        logger.info("收到快速导出Excel请求")
        
        # 获取前端传来的数据
        fields_data = request.get("fields_data", {})
        filename_prefix = request.get("filename_prefix", "报关单")
        
        if not fields_data:
            raise HTTPException(status_code=400, detail="没有提供字段数据")
        
        # 初始化Excel服务
        excel_service = ExcelExportService()
        
        # 构造格式化结果（模拟extract_service的输出格式）
        formatted_results = {
            "fields_data": fields_data,
            "success": True,
            "message": "数据已由前端提供"
        }
        
        # 生成Excel文件
        excel_path = excel_service.create_extraction_excel(
            formatted_results,
            filename_prefix=filename_prefix
        )
        
        # 返回文件下载
        import os
        filename = os.path.basename(excel_path)
        
        return FileResponse(
            path=excel_path,
            filename=filename,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"快速导出Excel失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"导出失败: {str(e)}")


@router.get("/test/rules")
async def get_extraction_rules():
    """
    获取所有提取规则（用于测试）
    """
    from app.core.constants import EXTRACTION_RULES
    return create_response(
        success=True,
        message="提取规则列表",
        data={
            "total_rules": len(EXTRACTION_RULES),
            "rules": EXTRACTION_RULES
        }
    )

